package com.colin.distributelock.controller;

import com.colin.distributelock.lock.ZookeeperLock;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Created by Colin on 2020/8/31 19:55
 * email: colinzhaodong@gmail.com
 * desc:
 *
 * @author zhaod
 */
@RestController
@Slf4j
public class ZookeeperController {
	@Resource
	private RedisTemplate redisTemplate;
	@Resource
	private CuratorFramework client;

	@GetMapping("zookeeper-lock")
	public String zookeeperLock() {
		log.info("我进入了方法");
		log.info("我进入了锁!");
		try (ZookeeperLock zkLock = new ZookeeperLock()) {
			if (zkLock.getLock("order")) {
				log.info("获取到了锁 ");
				Thread.sleep(15000);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		log.info("方法执行完成,锁释放");
		return "方法执行完成";
	}

	@GetMapping("curator-lock")
	public String curatorLock() throws Exception {
		InterProcessMutex lock = new InterProcessMutex(client, "/order");
		try {
			if (lock.acquire(30, TimeUnit.SECONDS)) {
				try {
					log.info("获取到了锁!");
					TimeUnit.SECONDS.sleep(10);
				} finally {
					lock.release();
					log.info("释放了锁");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "程序执行完成";
	}
}
